package cn.edu.csust.coursecard.interceptor;

import cn.edu.csust.coursecard.common.CodeEnum;
import cn.edu.csust.coursecard.dao.dto.RedisKeyConstant;
import cn.edu.csust.coursecard.exception.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 博客模块的拦截器
 * 作用：判断用户是否禁言
 */
@Component
public class MuteInterceptor implements HandlerInterceptor {
    
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    
    private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Integer userId = (Integer) request.getAttribute("userId");
        Boolean mute = redisTemplate.hasKey(RedisKeyConstant.MUTE + userId);
        if(mute != null && mute){
            Long expire = redisTemplate.getExpire(RedisKeyConstant.MUTE + userId);
            throw new BaseException(CodeEnum.MUTE_ERROR.getCode(), "你已被禁言,结束时间为："+ simpleDateFormat.format(new Date(System.currentTimeMillis() + expire*1000)));
        }
        return true;
    }
}
